package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    //微信体检预约
    @RequestMapping("/submit")
    //因为前端信息传入于任何实体类都不匹配，所以用Map接收
    private Result submitOrder(@RequestBody Map map){

        //获取前台输入的验证码
         String validateCode = (String) map.get("validateCode");

         //从redis数据库中查询验证码
        String telephone = (String) map.get("telephone");
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //首先比对验证码
        if(validateCode != null && code != null && validateCode.equals(code)){
         //验证码正确
            //设置预约类型为微信预约
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//预约类型 电话预约/微信预约
            Result result = null;
            try {
                result = orderService.order(map);//通过dubbo远程调用服务实现预约的复杂业务逻辑
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
            if(result.isFlag()){
                //预约成功,发送短信通知客户
                String orderDate = (String) map.get("orderDate");
                try {
                    //短信通知因为需要企业资质权限，所以这里以验证码的形式代替，本来是传的orderDate
                    SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,"0000");
                } catch (ClientException e) {
                    e.printStackTrace();
                }

            }
            return result;

        }else {
            //验证码不正确
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //根据id查询预约信息 member setmeal orderDate orderType
    @RequestMapping("/findById")
    public Result findById(Integer id){
        /*<p>体检人：{{orderInfo.member}}</p>
        <p>体检套餐：{{orderInfo.setmeal}}</p>
        <p>体检日期：{{orderInfo.orderDate}}</p>
        <p>预约类型：{{orderInfo.orderType}}</p>*/
        try {
            //查询预约信息成功
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            //查询预约信息失败
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
